package com.stress.testing.common;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;

public class AgentExtendJarClassLoader extends URLClassLoader {
    private AgentJarClassMatcher agentJarClassMatcher;
    private URL[] urls;

    public AgentExtendJarClassLoader(URL[] urls, ClassLoader parent, AgentJarClassMatcher agentJarClassMatcher) {
        super(urls, parent);
        this.urls = urls;
        this.agentJarClassMatcher = agentJarClassMatcher;
    }

    public AgentExtendJarClassLoader(URL[] urls, AgentJarClassMatcher agentJarClassMatcher) {
        super(urls);
        this.urls = urls;
        this.agentJarClassMatcher = agentJarClassMatcher;
    }

    public AgentExtendJarClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory, AgentJarClassMatcher agentJarClassMatcher) {
        super(urls, parent, factory);
        this.urls = urls;
        this.agentJarClassMatcher = agentJarClassMatcher;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            // 1、检查已加载的类
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                if (agentJarClassMatcher.match(name)) {
                    // 2、自己先加载类：这里打破了双亲委派机制
                    c = findClass(name);
                } else {
                    long t0 = System.nanoTime();
                    try {
                        // 3、使用父ClassLoader加载类
                        c = getParent().loadClass(name);
                    } catch (ClassNotFoundException e) {
                        // ClassNotFoundException thrown if class not found
                        // from the non-null parent class loader
                    }

                    if (c == null) {
                        // If still not found, then invoke findClass in order
                        // to find the class.
                        long t1 = System.nanoTime();
                        // 4、自己加载类
                        c = findClass(name);

                        // this is the defining class loader; record the stats
                        sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                        sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                        sun.misc.PerfCounter.getFindClasses().increment();
                    }
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }
}
